function updateWinnerPlayers()
{
	selectBox = $("#winnerPlayer")[0];
	falseBox = $("#falseMahjongPlayer")[0];
	
	for (i = selectBox.length - 1; i >= 0; i--) {
		selectBox.remove(i);
	}
	for (i = falseBox.length - 1; i >= 0; i--) {
		falseBox.remove(i);
	}
	
	for (i = 0; i < 4; i++) {
		playerId = "#id_player" + i + "Name";
		
		o = new Option($(playerId).val(), i);		
		selectBox.options[selectBox.length] = o;
		
		o = new Option($(playerId).val(), i);
		falseBox.options[falseBox.length] = o;
	}
	
	updateByPlayers();
}

function updateByPlayers()
{
	byBox = $("#byPlayer")[0];
	
	for (i = byBox.length - 1; i >= 0; i--) {
		o = byBox.options[i];
		v = o.value;
		
		if (v >= 0) {
			byBox.remove(i);
		}
	}
	
	for (i = 0; i < 4; i++) {
		if (i == $("#winnerPlayer").val()) continue;
		
		playerId = "#id_player" + i + "Name";
		
		o = new Option($(playerId).val(), i);
		
		byBox.options[byBox.length] = o; 
	}
}

function fansCustomInputted()
{
    falseMahjongFans = [0, 0, 0, 0];
    calculatedFans = [0, 0, 0, 0];
}

function updateFansInput()
{
    for (i = 0; i < 4; i++) {
        fanInputId = "#id_player" + i + "Fan";
        $(fanInputId).val(falseMahjongFans[i] + calculatedFans[i]); 
    }
}

$(function() {
	updateWinnerPlayers();
	
	$("#winnerPlayer").change(updateByPlayers);
	for (i = 0; i < 4; i++) {
		playerId = "#id_player" + i + "Name";
		$(playerId).change(updateWinnerPlayers); 
	}
	
	for (i = 0; i < 4; i++) {
        fanInputId = "#id_player" + i + "Fan";
        $(fanInputId).change(fansCustomInputted); 
    }
	
    var onPlayControlSubmitFailed = function() {
        $("#playControlSubmit")[0].disabled = false;
        currentFanArr = null;
        
        if (!modifying) {
            $("#sessionTable")[0].deleteRow(2);
            
            for (i = 0; i < 4; i++) {
                $("#sumFan_" + i).html(sumFanArr[i]);
            }
        }
    };
    
    $("#playControlSubmit").click(function() {
        if (currentFanArr != null) {    //last AJAX communication is not finished yet
            return false;
        }
        
        $(".form_err_msg").css("visibility", "hidden")
        
        var f = true;
        
        if (!isInteger($("#id_player0Fan").val())) {
            $("#player0Err").css("visibility", "visible");
            f=false;
        }
        if (!isInteger($("#id_player1Fan").val())) {
            $("#player1Err").css("visibility", "visible");
            f=false;
        }
        if (!isInteger($("#id_player2Fan").val())) {
            $("#player2Err").css("visibility", "visible");
            f=false;
        }
        if (!isInteger($("#id_player3Fan").val())) {
            $("#player3Err").css("visibility", "visible");
            f=false;
        }
        
        currentFanArr = [0, 0, 0, 0];
        
        for (i = 0; i < 4; i++) {
            playerId = "#id_player" + i + "Name";
            fanId = "#id_player" + i + "Fan";
            
            playerName = $(playerId).val();
            playerFan = parseInt($(fanId).val());
            
            if (!(playerName in playerPosition)) {
                $("#generalErr").html(generalErrorText["playersNotSame"]);
                $("#generalErr").css("visibility", "visible");
                f = false;
            }
            
            currentFanArr[playerPosition[playerName]] = playerFan;
        }
        
        if (!f) {
            currentFanArr = null;
            return false;
        }
        
        $("#playControlSubmit")[0].disabled = true;
        
        dataArr = {
                   "handNumber" : handNumber,
                   "sessionNumber" : sessionNumber, 
                   "gameKeyStr" : gameKeyStr, 
                   "playerArr": 
                                $("#id_player0Name").val() + "," +
                                $("#id_player1Name").val() + "," +
                                $("#id_player2Name").val() + "," +
                                $("#id_player3Name").val(),
                   "playerFanArr": 
                                $("#id_player0Fan").val() + "," +
                                $("#id_player1Fan").val() + "," +
                                $("#id_player2Fan").val() + "," +
                                $("#id_player3Fan").val()};
        
        $.ajax({
            type: "POST",
            url: "/game/official_mahjong/playhand/",
            data: dataArr,
            dataType: "json",
            success: function(data, textStatus) {
                if (data["success"]) {
                	if (modifying) {
                		window.location = "/play/official_mahjong/" + gameKeyStr + "/";
                        return false;
                	}
                	
                    for (i = 0; i < 4; i++) {
                        sumFanArr[i] += currentFanArr[i];
                    }
                    
                    currentFanArr = null;
                    
                    if (handNumber + 1 >= 16) {
                        window.location.reload();
                        return false;
                    }
                    
                    $("#id_player0Name").val(data["playerArr"][0]);
                    $("#id_player1Name").val(data["playerArr"][1]);
                    $("#id_player2Name").val(data["playerArr"][2]);
                    $("#id_player3Name").val(data["playerArr"][3]);
                    
                    $("#id_player0Fan").val("");
                    $("#id_player1Fan").val("");
                    $("#id_player2Fan").val("");
                    $("#id_player3Fan").val("");
                    
                    updateWinnerPlayers();
                    
                    handNumber++;
                    
                    $("#roundWind").html(directionName[(handNumber / 4 | 0) % 4]);
                    $("#seatWind").html(directionName[handNumber % 4]);
                    
                    fansCustomInputted();
                    
                    $("#playControlSubmit")[0].disabled = false;
                }
                else {
                    $("#generalErr").html(generalErrorText[data["errorName"]]);
                    $("#generalErr").css("visibility", "visible");
                    
                    onPlayControlSubmitFailed();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                onPlayControlSubmitFailed();
            }
        });
        
        if (!modifying) {
            var newRow = $("#sessionTable")[0].insertRow(2);
            
            var newCell = newRow.insertCell(-1);
            $(newCell).html(directionName[(handNumber / 4 | 0) % 4]);
            
            newCell = newRow.insertCell(-1);
            $(newCell).html(directionName[handNumber % 4]);
            
            for (i = 0; i < 4; i++) {
                newCell = newRow.insertCell(-1);
                $(newCell).html(currentFanArr[i]);
                
                $("#sumFan_" + i).html(sumFanArr[i] + currentFanArr[i]);
            }
            
            newCell = newRow.insertCell(-1);
            $(newCell).html(sprintf(newRowEditCell, handNumber));
        }
        
        return false;
    });
    
    $("#calculateButton").click(function() {
        $("#winnerFanErr").css("visibility", "hidden");
        
        if (!isInteger($("#winnerFan").val())) {
            $("#winnerFanErr").css("visibility", "visible");
            return false;
        }
        
        var winnerFan = parseInt($("#winnerFan").val());
        var winnerPlayer = $("#winnerPlayer").val();
        var byPlayer = $("#byPlayer").val();
        
        var wonFan = 0;
        
        for (i = 0; i < 4; i++) {
            if (i == winnerPlayer) continue;
            
            if (i == byPlayer || byPlayer == -1) {
                calculatedFans[i] = -8 - winnerFan;
            }
            else {
                calculatedFans[i] = -8;
            }
            
            wonFan += - calculatedFans[i];
        }
        
        calculatedFans[winnerPlayer] = wonFan;
        
        updateFansInput();
    });
    
    $("#falseMahjongValidButton").click(function() {
        falsePlayer = $("#falseMahjongPlayer").val();
        
        for (i = 0; i < 4; i++) {
            if (i == falsePlayer) {
                falseMahjongFans[i] += -30;
            }
            else {
                falseMahjongFans[i] += 10;
            }
        }
        
        updateFansInput();
    });
    
    $("#falseMahjongInvalidButton").click(function() {
        falsePlayer = $("#falseMahjongPlayer").val();
        
        for (i = 0; i < 4; i++) {
            if (i == falsePlayer) {
                falseMahjongFans[i] += -60;
            }
            else {
                falseMahjongFans[i] += 20;
            }
        }
        
        updateFansInput();
    });
    
    $("#drawGameButton").click(function() {
        for (i = 0; i < 4; i++) {
            fanInputId = "#id_player" + i + "Fan";
            $(fanInputId).val(0); 
        }
        
        fansCustomInputted();
    });
    
});
  
